//
//  ViewController.m
//  19-JSON
//
//  Created by 鹏飞罗 on 16/8/9.
//  Copyright © 2016年 罗鹏飞. All rights reserved.
//

#import "ViewController.h"
#import "CustomCollectionViewLayout.h"
#import "contentTitle.h"
#import "TitleCollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CustomCollectionViewLayoutDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (nonatomic, strong) NSMutableArray <ContentTitle *> *contentTitleArray;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
   // JSON 解析
   // 通过一个Data， 将对应的格式转换成OC认识的内容
   // 数组/字典
    [self handleData];
       CustomCollectionViewLayout *layout = (CustomCollectionViewLayout *)self.myCollectionView.collectionViewLayout;
    layout.delegate = self;
    
}
- (void) handleData {
    _contentTitleArray = [NSMutableArray array];
    // 获取JSON的data
    NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"FirstJSON" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:dataPath];
  // JSON解析
    NSError *error = nil;
  NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    NSArray *list = jsonDic[@"tabs"] [@"list"];
    for (NSDictionary *contentDic in list) {
        ContentTitle *contentTitle = [ContentTitle contentTitleWithDictionary:contentDic];
        [_contentTitleArray addObject:contentTitle];
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout*)collectionViewLayout
                   height:(CGFloat)height
  widthForItemAtIndexPath:(NSIndexPath *)indexPath {
    ContentTitle *contentTitle = _contentTitleArray[indexPath.row];
 CGRect newRect = [contentTitle.title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.myCollectionView.bounds)) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
     CGFloat width = ceilf(newRect.size.width);
    return width;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _contentTitleArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   TitleCollectionViewCell  *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.contentTitle = _contentTitleArray[indexPath.row];
    
    return cell;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
